package com.demo.多线程;

/**
 * @Program: java
 * @ClassName Race
 * @Author: liutao
 * @Description: 龟兔赛跑
 * @Create: 2023-10-26 22:23
 * @Version 1.0
 **/


public class Race implements Runnable {

    private static String winner;

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
                try {
                    // 模拟兔子睡觉
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            // 比赛结束
            if (gameOver(i)) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "-->" + i + "步");
        }
    }

    private boolean gameOver(int i) {
        if (winner != null) {
            return true;
        } else {
            if (i >= 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner=" + winner);
                return true;
            }
        }
        return false;
    }
}
